﻿using DigitalHealth.PACS.Common.Exceptions;
using IdentityModel;
using IdentityServer4.Validation;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace DigitalHealth.PACS.IdentityService.IdentityServer
{
    public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        private readonly UserManager<IdentityUser> _userManager;
        private readonly SignInManager<IdentityUser> _signInManager;

        public ResourceOwnerPasswordValidator(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }


        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            var user = _userManager.Users.Where(u => u.UserName == context.UserName).FirstOrDefault();

            if (user == null)
            {
                throw new BizException($"用户不存在:{context.UserName}");
            }
            if (!await _userManager.CheckPasswordAsync(user, context.Password))
            {
                throw new BizException($"用户密码不正确");
            }

            context.Result = new GrantValidationResult(
                        subject: user.Id.ToString(),
                        authenticationMethod: user.UserName,
                        claims: GetUserClaims(user));
            await Task.CompletedTask;
        }

        public Claim[] GetUserClaims(IdentityUser user)
        {
            return new Claim[]
            {
                new Claim(JwtClaimTypes.Subject, user.Id.ToString() ?? ""),
                new Claim(JwtClaimTypes.Id, user.Id.ToString() ?? ""),
                new Claim(JwtClaimTypes.Name, user.UserName?? ""),
                new Claim(JwtClaimTypes.PhoneNumber, user.PhoneNumber  ?? "")
            };
        }
    }
}
